import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore, useAdminStore } from '@/stores'
const router = createRouter({
  history: createWebHistory('/'),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/login/LoginPage.vue')
    },
    {
      path: '/',
      component: () => import('@/views/layout/LayoutUser.vue'),
      children: [
        {
          path: '/user/userpersonal',
          component: () => import('@/views/user/UserPersonal.vue')
        },
        {
          path: '/user/useraccount',
          component: () => import('@/views/user/UserAccount.vue')
        }
      ],
      redirect: '/user/userpersonal'
    },
    {
      path: '/admin',
      component: () => import('@/views/layout/LayoutAdmin.vue'),
      children: [
        {
          path: '/admin/adminexpert',
          component: () => import('@/views/admin/AdminExpert.vue')
        },
        {
          path: '/admin/adminpotexpert',
          component: () => import('@/views/admin/AdminPotExpert.vue')
        },
        {
          path: '/admin/admincenter',
          component: () => import('@/views/admin/AdminCenter.vue')
        }
      ],
      redirect: '/admin/adminexpert'
    }
  ]
})
//全局前置守卫
router.beforeEach((to) => {
  const UserStore = useUserStore()
  const AdminStore = useAdminStore()
  const hasUserToken = UserStore.token
  const hasAdminToken = AdminStore.token

  // 1. 没有任何token，只能去登录页
  if (!hasUserToken && !hasAdminToken) {
    if (to.path !== '/login') return '/login'
    return true
  }

  // 2. 只有userToken
  if (hasUserToken && !hasAdminToken) {
    // 只允许访问用户相关路由
    if (to.path.startsWith('/admin')) {
      return '/user/userpersonal'
    }
    return true
  }

  // 3. 只有adminToken
  if (!hasUserToken && hasAdminToken) {
    // 只允许访问管理员相关路由
    if (to.path.startsWith('/user')) {
      return '/admin/adminexpert'
    }
    return true
  }

  // 4. 两个token都有，全部可访问
  return true
})
export default router
